package com.liwei.lwmail.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.liwei.common.exception.NoStockException;
import com.liwei.common.to.mq.OrderTo;
import com.liwei.common.to.mq.StockDetailTo;
import com.liwei.common.to.mq.StockLockedTo;
import com.liwei.common.utils.R;
import com.liwei.lwmail.ware.entity.WareOrderTaskDetailEntity;
import com.liwei.lwmail.ware.entity.WareOrderTaskEntity;
import com.liwei.lwmail.ware.feign.OrderFeignService;
import com.liwei.lwmail.ware.feign.ProductFeignService;
import com.liwei.lwmail.ware.service.WareOrderTaskDetailService;
import com.liwei.lwmail.ware.service.WareOrderTaskService;
import com.liwei.lwmail.ware.vo.OrderItemVo;
import com.liwei.lwmail.ware.vo.OrderVo;
import com.liwei.lwmail.ware.vo.SkuHasStockVo;
import com.liwei.lwmail.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liwei.common.utils.PageUtils;
import com.liwei.common.utils.Query;

import com.liwei.lwmail.ware.dao.WareSkuDao;
import com.liwei.lwmail.ware.entity.WareSkuEntity;
import com.liwei.lwmail.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {


    @Autowired
    private WareSkuDao wareSkuDao;
    @Autowired
    private ProductFeignService feignService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private WareOrderTaskService orderTaskService;
    @Autowired
    private WareOrderTaskDetailService orderTaskDetailService;
    @Autowired
    private OrderFeignService orderFeignService;



    private void unlockStock(Long skuId, Long wareId, int num, Long taskDetailId){
        baseMapper.unlockStock(skuId,wareId,num);

        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(taskDetailId);
        detailEntity.setLockStatus(2);//更改库存锁定状态，2-已解锁
        orderTaskDetailService.updateById(detailEntity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }
        if (!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //判断是否有过库存记录，就是新增操作
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuEntities.size() == 0 || wareSkuEntities == null){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            //远程查询sku的名字
            //TODO 如何不使用try-catch ，也可以使事务不回滚
            try{
                R info = feignService.info(skuId);
                Map<String,Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0){
                    wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            wareSkuDao.insert(wareSkuEntity);
        }
        wareSkuDao.addStock(skuId, wareId, skuNum);
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(id -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            vo.setSkuId(id);
            //查询当前sku的总库存量 SELECT SUM(stock-stock_locked) FROM wms_ware_sku WHERE sku_id = 1
            Long stock = baseMapper.getSkuStock(id);
            vo.setHasStock(stock != null && stock > 0);

            return vo;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 库存自动解锁的场景
     * 1、下订单成功，订单超时未支付/被用户手动取消
     * 2、下订单成功，库存也锁定成功，但是业务调用失败，导致订单回滚
     * @param lockVo
     */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo lockVo) {
        //保存库存工作单的详情 -- 追溯锁定详情
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(lockVo.getOrderSn());
        orderTaskService.save(taskEntity);


        //1、找到每个商品在哪个仓库都有库存
        List<OrderItemVo> orderItems = lockVo.getOrderItems();
        List<SkuWareHasStock> collect = orderItems.stream().map(item -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            skuWareHasStock.setSkuId(skuId);
            skuWareHasStock.setNum(item.getCount());

            List<Long> wareIds = baseMapper.selectWareIdsHasSkuStock(skuId);
            skuWareHasStock.setWareIds(wareIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());

        //2、锁定库存
        for (SkuWareHasStock stock : collect) {
            boolean skuLock =false;
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareIds();
            if (wareIds == null || wareIds.size() == 0){
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                Long count = baseMapper.lock(skuId, wareId, stock.getNum());
                if (count == 1){
                    skuLock = true;
                    //库存锁定成功，告诉MQ库存锁定成功
                    WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
                    detailEntity.setSkuId(skuId);
                    detailEntity.setSkuNum(stock.getNum());
                    detailEntity.setTaskId(taskEntity.getId());
                    detailEntity.setWareId(wareId);
                    detailEntity.setLockStatus(1);
                    orderTaskDetailService.save(detailEntity);
                    //发送消息
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());

                    StockDetailTo detailTo = new StockDetailTo();
                    BeanUtils.copyProperties(detailEntity,detailTo);
                    lockedTo.setDetailTo(detailTo);
                    rabbitTemplate.convertAndSend("stock.event.exchange","stock.locked",lockedTo);
                    break;
                }
            }
            if (!skuLock){
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }

        //全部锁定成功
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {

        //解锁库存
        StockDetailTo detailTo = to.getDetailTo();
        Long detailId = detailTo.getId();
        //1、查询数据库关于这个订单锁定库存的消息
        WareOrderTaskDetailEntity detailEntity = orderTaskDetailService.getById(detailId);
        if (detailEntity != null){
            //有：需要解锁
            Long id = to.getId();//库存工作单id
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            //根据订单号查询订单状态:已取消状态才能解锁库存
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0){
                //订单数据返回成功
                OrderVo orderVo = r.getData(new TypeReference<OrderVo>() {});
                if (orderVo == null || orderVo.getStatus() == 4){
                    //订单不存在/已经被取消，解锁库存
                    if(detailEntity.getLockStatus() == 1){
                        unlockStock(detailTo.getSkuId(),detailTo.getWareId(),detailTo.getSkuNum(),detailId);
                    }
                }
            }else {
                throw new RuntimeException("远程服务失败");
            }

        }else {
            //没有：说明库存锁定失败，库存已经回滚，此时库存无需解锁
        }
    }

    /**
     * 防止订单卡顿延迟失败，导致库存无法解锁
     * @param orderTo
     */
    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查询最新工作单的状态，防止重复解锁库存
        WareOrderTaskEntity orderTaskEntity = orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = orderTaskEntity.getId();
        //按照工作单找到所有未解锁的库存进行解锁
        List<WareOrderTaskDetailEntity> list = orderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>()
                        .eq("task_id", id)
                        .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity detailEntity : list) {
            unlockStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum(),detailEntity.getId());
        }
    }

    @Data
    static class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareIds;
    }
}